//全局变量区
var searchDiv    = document.getElementById('searchDiv');
searchComp   = document.getElementById('autoComplete');
searchName   = document.getElementById('searchName');
isOnAutoComp = false;//鼠标是否在自动补全列表上
//*****

//监听器事件区
searchName.addEventListener('keyup',onSearchKeyUp);//输入结束时，查询，显示
searchName.addEventListener('blur',onSearchBlur);//失去焦点时，隐藏
searchComp.addEventListener('mouseenter',setTrue);
searchComp.addEventListener('mouseleave',setFalse);//鼠标进入离开
//*****

//自动补全部分代码
function onSearchKeyUp(){
    $('#autoCompleteLi').empty();//先清空

    var searchString = $('#searchName').val();//获取当前输入框的字符
    //console.log(searchString);

    //如果有输入的话，查询
    if(searchString !== '' && searchString.length !== 0){
        $.ajax({
            type:'GET',
            url :'http://localhost:8080/petstore/autoComplete?searchString='+searchString,
            success : function (data){
                var dataJson = JSON.parse(data);//取得响应，转换为JSON
                var autoInnerHtml='';
                //console.log(dataJson);
                $('#autoCompleteLi').empty();//先清空
                //循环取值，拼接并显示
                for(var i in dataJson){
                    if(i>6) break;//超过7个则停止
                    autoInnerHtml+='<ul class=\"searchCompUl\" data-name=\"'
                        +dataJson[i].name+'\">'
                        +dataJson[i].name+'</ul>';//拼接
                }
                $('#autoCompleteLi').append(autoInnerHtml);//添加
            },
            error : function (errorMsg){
                console.log(errorMsg);
            },
        });
        searchComp.style.display="block";//显示出来
    }
}//查询并显示

$('#autoCompleteLi').on('click','.searchCompUl',function (){
    var autoCompleteName = $(this).data('name');
    $('#searchName').val(autoCompleteName);
    //补全至搜索框后，清空并隐藏
    $("#autoCompleteUl").empty();
    searchComp.style.display="none";
});//动态绑定点击事件

function onSearchBlur(){
    if(!isOnAutoComp){
        console.log(isOnAutoComp);
        $("#autoCompleteUl").empty();
        searchComp.style.display="none";
    }
}//清空并隐藏

//设置是否处于自动补全div内状态
function setFalse(){
    isOnAutoComp=false;
}
function setTrue(){
    isOnAutoComp=true;
}
//*****